Page({
  data: {
    storeCode: '',
    deviceCode: '',
    batteryOldCode: '',
  },
  handleScan(event) {
    const type = event.currentTarget.dataset.code;
    const that = this;
    wx.scanCode({
      success: (res) => {
        that.setData({
          [type]: res.result
        })
      }
    })
  },
  formSubmit(e) {
    if (!e.detail.value.storeCode) {
      return wx.showToast({
        icon: 'none',
        title: '门店信息不能为空',
      })
    }
    if (!e.detail.value.deviceCode) {
      return wx.showToast({
        icon: 'none',
        title: '设备编码不能为空',
      })
    }
    if (!e.detail.value.batteryOldCode) {
      return wx.showToast({
        icon: 'none',
        title: '原电池编码不能为空',
      })
    }
    const userID = wx.getStorageSync('userID')
    const data = {
      ...e.detail.value,
      createdAt: new Date().getTime(),
      userID
    }
    console.log('data===', data)
    this.create(data)
  },
  async create(data) {
    const {
      batteryOldCode,
      deviceCode
    } = data

    if (this.startsWithField(batteryOldCode, '123')) {
      return wx.showToast({
        icon: 'none',
        title: '该电池已是最新电池',
      })
    }

    let res = await wx.cloud.database().collection('information')
      .where({
        deviceCode
      })
      .get()

    if (res.data && res.data.length > 0) {
      const info = res.data[0]
      if (!!info.batteryNewCode) {
        return wx.showToast({
          icon: 'none',
          title: '该设备电池已更换',
        })
      } else {
        return wx.showToast({
          icon: 'none',
          title: '该设备已登记',
        })
      }
    }
    wx.cloud.database().collection('information')
      .add({
        data
      })
      .then(res => {
        wx.showToast({
          title: '添加成功',
          icon: 'success'
        })
        wx.navigateBack();
      }).catch(err => {
        wx.showToast({
          title: err,
          icon: 'error'
        })
      })
  },
  startsWithField(str, field) {
    const regex = new RegExp(`^${field}`);
    return regex.test(str);
  }
})